﻿#include "commands.h"
#include "graphicsitem.h"

Commands::Commands(GraphicsItem::EGraphicsType addType, QGraphicsScene *scene, QUndoCommand *parent)
    :QUndoCommand(parent)
{
    static int itemCount = 0;

    m_GraphicsScene = scene;
    m_pGraphicsItem = new GraphicsItem(addType);
    initialPosition = QPointF((itemCount * 15) % int(scene->width()),
                              (itemCount * 15) % int(scene->height()));
    scene->update();
    itemCount++;
    setText(QObject::tr("Add %1")
        .arg(createCommandString(m_pGraphicsItem, initialPosition)));
}

Commands::~Commands()
{
    if(!m_pGraphicsItem->scene())
    {
        delete m_pGraphicsItem;
    }
}

void Commands::undo()
{
    m_GraphicsScene->removeItem(m_pGraphicsItem);
    m_GraphicsScene->update();
}

void Commands::redo()
{
    m_GraphicsScene->addItem(m_pGraphicsItem);
    m_pGraphicsItem->setPos(initialPosition);
    m_GraphicsScene->clearSelection();
    m_GraphicsScene->update();
}

QString Commands::createCommandString(GraphicsItem *item, const QPointF &pos)
{
    return QObject::tr("%1 at (%2, %3)")
        .arg(item->diagramType() == GraphicsItem::Box ? "Box" : "Triangle")
        .arg(pos.x()).arg(pos.y());
}
